import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Delivery } from "src/modules/delivery/delivery.entity";
import { Order } from "src/modules/order/order.entity";
import { Repository } from "typeorm";
import { DeliveryItem } from "./delivery-item.entity";

@Injectable()
export class DeliveryItemService {
  constructor(
    @InjectRepository(DeliveryItem)
    private readonly deliveryItemRepository: Repository<DeliveryItem>
  ) {}

  async findAll(): Promise<[DeliveryItem[], number]> {
    return await this.deliveryItemRepository.findAndCount({
      relations: ["order", "delivery"],
    });
  }
  find(deliveryItem: string | DeliveryItem): Promise<DeliveryItem> {
    const id =
      deliveryItem instanceof DeliveryItem ? deliveryItem.id : deliveryItem;
    return this.deliveryItemRepository.findOneOrFail(id, {
      relations: ["order", "delivery"],
    });
  }
  findByOrder(order: Order): Promise<[DeliveryItem[], number]> {
    return this.deliveryItemRepository.findAndCount({
      order,
    });
  }
  findByDelivery(delivery: Delivery): Promise<[DeliveryItem[], number]> {
    return this.deliveryItemRepository.findAndCount({
      delivery,
    });
  }
}
